import * as CryptoJS from 'crypto-js'

const AES_KEY = 'Hox%Q1k9h4uIve^2'
const AES_IV = 'U29i@39*#32)df23'

/**
 * SHA256 哈希
 * @param message 数据
 */
export const hashSHA256 = (message: string): string => {
  return CryptoJS.SHA256(message).toString(CryptoJS.enc.Hex)
}

/**
 * AES 加密
 * @param message 数据
 * @param key 密钥
 * @param iv 初始向量
 */
export const encryptAES = (message: string, key = AES_KEY, iv = AES_IV): string => {
  const keyWordArray = CryptoJS.enc.Utf8.parse(key)
  const ivWordArray = CryptoJS.enc.Utf8.parse(iv)
  return CryptoJS.AES.encrypt(message, keyWordArray, {
    iv: ivWordArray }).toString()
}

/**
 * AES 解密
 * @param message 数据
 * @param key 密钥
 * @param iv 初始向量
 */
export const decryptAES = (message: string, key = AES_KEY, iv = AES_IV): string => {
  const keyWordArray = CryptoJS.enc.Utf8.parse(key)
  const ivWordArray = CryptoJS.enc.Utf8.parse(iv)
  return CryptoJS.AES.decrypt(message, keyWordArray, {
    iv: ivWordArray }).toString(CryptoJS.enc.Utf8)
}

/**
 * 计算文件MD5值
 * @param result 数据
 */
export const getFileMD5 = (result: ArrayBuffer): string => {
  const wordArray = CryptoJS.lib.WordArray.create(result)
  return CryptoJS.MD5(wordArray).toString(CryptoJS.enc.Hex)
}

/**
 * Base64 编码加密
 * @param message 数据
 */
export const encodeBase64 = (message: string): string => {
  return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(message))
}

/**
 * Base64 解码
 * @param base64String 数据
 */
export const decodeBase64 = (base64String: string): string => {
  const bytes = CryptoJS.enc.Base64.parse(base64String)
  return bytes.toString(CryptoJS.enc.Utf8)
}
